import React, { Component } from 'react';
import Child from './components/Child carr';

class App extends Component {
  arr = [
    {
      username: 'tom',
      password: '123',
      nianling: 18
    },
    {
      username: 'jerry',
      password: '123',
      nianling: 18
    }]
  state = {
    username: {
      value: '',
      onChange: e => this.setState(state => ({ username: { ...state.username, value: e.target.value } })),
    },
    password: {
      value: '',
      onChange: e => this.setState(state => ({ password: { ...state.password, value: e.target.value } }))
    },
    nianling: {
      value: '',
      onChange: e => this.setState(state => ({ nianling: { ...state.nianling, value: e.target.value } }))
    }
  }

  login = () => {
    console.log(this.state.nianling.value);
    const { username, password, nianling } = this.state
    // 非空判断
    if (!username.value || !password.value || !nianling.value) return alert('请完整填写')
    // 账号不重复
    if (this.arr.some(i => i.username === username.value)) return alert('账号重复')
    // 判断密码长度
    if (password.value.length < 3 || password.value.length > 5) return alert('密码长度3-5')
    // 年龄判断
    if (nianling.value < 1 || nianling.value > 200) return alert('年龄1-200')
    let obj = {
      username: username.value,
      password: password.value,
      nianling: nianling.value
    }
    this.arr.push(obj)
    this.forceUpdate()
    this.setState({ username: { ...this.state.username, value: '' } })
    this.setState({ password: { ...this.state.password, value: '' } })
    this.setState({ nianling: { ...this.state.nianling, value: '' } })
    this.setState({
      arr: [...this.arr, obj]
    })
  }
  // fn = () => console.log('fn');

  render() {
    return (
      <div className="box">
        <div>
          账号：
          <input
            type="text"
            {...this.state.username}
          />
        </div>
        <div>
          密码：
          <input
            type="text"
            {...this.state.password}
          />
        </div>
        <div>
          年龄：
          <input
            type="text"
            {...this.state.nianling}
          />
        </div>
        <div>
          <button onClick={this.login}>添加</button>
        </div>
        <Child arr={this.arr} />
      </div>
    );
  }
}

export default App;
